package com.junjie.index12306.biz.wxservice.handler.chatApi;// Copyright (c) Alibaba, Inc. and its affiliates.

import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.aigc.generation.models.QwenParam;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.MessageManager;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.junjie.index12306.biz.wxservice.utils.RedisUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class QWENChatApi implements ChatApiHandler, InitializingBean {
    private String apikey;
    @Autowired
    private RedisUtil redisUtil;

    @Override
    public String dealMsgAndCall(String message) {
        String replyMessage = null;
        try {
            replyMessage = callWithMessage(message);
        } catch (Throwable e) {
            log.error("chatApi错误,{}",e.getMessage());
            return "chatApi错误，请联系管理员";
        }
        return replyMessage;
    }

    public String callWithMessage(String message)
            throws NoApiKeyException, ApiException, InputRequiredException {

        Generation gen = new Generation();
        MessageManager msgManager = new MessageManager(10);
        Message systemMsg =
                Message.builder().role(Role.SYSTEM.getValue()).content("You are a helpful assistant.").build();
        Message userMsg = Message.builder().role(Role.USER.getValue()).content(message).build();
        msgManager.add(systemMsg);
        msgManager.add(userMsg);
        String model = redisUtil.get("qwen-model");
        QwenParam param =
                QwenParam.builder().model(model).messages(msgManager.get())
                        .resultFormat(QwenParam.ResultFormat.MESSAGE)
                        .apiKey(apikey)
                        .build();
        GenerationResult result = gen.call(param);
        String resultContent = result.getOutput().getChoices().get(0).getMessage().getContent();
        return resultContent;
    }


    public static void main(String[] args) {
        QWENChatApi QWENChatApi = new QWENChatApi();
        Date startDate = new Date();
        String s = "ai/瘦下来会发生什么变化，字可以少点，快速生成";
        try {
            String resultContent = QWENChatApi.callWithMessage(s);
            System.out.println(resultContent);
            Date endDate = new Date();
            System.out.println(getDifferenceInMinutes(startDate, endDate));
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            System.out.println(e.getMessage());
        }
        System.exit(0);
    }


    /**
     * 计算两个日期之间的差值（分钟）
     *
     * @param startDate 起始日期
     * @param endDate   结束日期
     * @return 相差的分钟数
     */
    public static long getDifferenceInMinutes(Date startDate, Date endDate) {
        long diffMillis = endDate.getTime() - startDate.getTime(); // 获取时间差（毫秒）
        return diffMillis / (1000); // 将毫秒转换为分钟
    }

    @Override
    public ChatApiTypeEnum getChatApiType() {
        return ChatApiTypeEnum.QWEN;
    }


    @Override
    public void afterPropertiesSet() throws Exception {
        this.apikey = redisUtil.get("qwen_api_key");
    }
}